package org.design.hotdevelop.register;

import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.design.hotdevelop.compile.CompileSource;
import org.design.hotdevelop.constant.PatternConstant;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;

/**
 * @description:
 * @author: freedom
 * @date: 2024/9/25
 **/
@Slf4j
@Component
public class LoadBeanService {

    public static final AtomicInteger ATOMIC_INTEGER = new AtomicInteger(0);
    public void loadSource (String sourceCode) {
        int i = ATOMIC_INTEGER.incrementAndGet();
        try {
            Matcher matcher = PatternConstant.CLASS_PATTERN.matcher(sourceCode);
            String packageName = extractPackageName(sourceCode);
            if (matcher.find()) {
                // 提取类名
                String className = matcher.group(1);
                if(i>0){
                    String replaceClassName = className + "_V_"+(i-1);
                    SpringUtil.unregisterBean(replaceClassName);
                }
               log.info("加载类:{}",className);
               String replaceClassName = className + "_V_"+i;
                try {
                    Object bean = SpringUtil.getBean(replaceClassName);
                    if(bean != null) {
                        log.info("try again replace class:{}!!!!",replaceClassName);
                        SpringUtil.unregisterBean(replaceClassName);
                    }
                }catch(Exception e) {
                   log.warn("bean:{} is not found, next....", replaceClassName);
                }
                String replace = sourceCode.replace(className,replaceClassName);
                Class<?> aClass = CompileSource.compileAndLoadClass(replace,packageName + "." + replaceClassName);
                log.info("loadBeanName:{}",replaceClassName);
                Object o = aClass.getDeclaredConstructor().newInstance();
                log.info("register bean:{}",o);
                SpringUtil.registerBean(replaceClassName,o);
            } else {
                log.info("No class name found.");
            }

        } catch (Exception e) {
            log.error("loadSource error :",e);
        }
    }

    /**
     * 从源代码字符串中提取包名
     *
     * @param sourceCode 源代码字符串
     * @return 包名，如果未找到则返回 null
     */
    public static String extractPackageName(String sourceCode) {
        // 正则表达式匹配 package 语句
        Matcher matcher = PatternConstant.PACKAGE_PATTERN.matcher(sourceCode);
        // 如果找到匹配项，则返回包名
        if (matcher.find()) {
            return matcher.group(1);
        }
        // 未找到 package 语句
        return null;
    }
}
